package io.github.jesse205.deskclock.lite.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

import androidx.annotation.Nullable;

import io.github.jesse205.deskclock.lite.R;
import io.github.jesse205.deskclock.lite.utils.DynamicSizeHelper;

public class DynamicTextView extends TextView {


    private DynamicSizeHelper dynamicSizeHelper;

    public DynamicTextView(Context context) {
        super(context);
    }

    public DynamicTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public DynamicTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr);
    }

    private void init(AttributeSet attrs, int defStyleAttr) {
        dynamicSizeHelper = new DynamicSizeHelper();
        // noinspection resource
        TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.DynamicTextView, defStyleAttr, 0);
        dynamicSizeHelper.setTextSizeWidthFactor(a.getFraction(R.styleable.DynamicTextView_textSizeWidthFactor, 1, 1, 0));
        dynamicSizeHelper.setTextSizeHeightFactor(a.getFraction(R.styleable.DynamicTextView_textSizeHeightFactor, 1, 1, 0));
        a.recycle();
    }

    public void setTextSizeWidthFactor(float factor) {
        dynamicSizeHelper.setTextSizeWidthFactor(factor);
        updateTextSize();
    }

    public float getTextSizeWidthFactor() {
        return dynamicSizeHelper.getTextSizeWidthFactor();
    }

    public void setTextSizeHeightFactor(float factor) {
        dynamicSizeHelper.setTextSizeHeightFactor(factor);
        updateTextSize();
    }

    public float getTextSizeHeightFactor() {
        return dynamicSizeHelper.getTextSizeHeightFactor();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        updateTextSize();
    }

    private void updateTextSize() {
        float textSize = dynamicSizeHelper.calculateTextSize(getMeasuredWidth(), getMeasuredHeight());
        if (textSize >= 0) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }
    }
}
